<script lang="ts" setup>
import { h, nextTick, reactive, toRefs } from 'vue'
import { CopyOutlined } from '@ant-design/icons-vue'
import Api from '@/api/'
import { PlayAudio } from '../index'
import { AddKeys, TurnText } from './index'
import to from '@/utils/awaitTo'
import { message } from 'ant-design-vue'
import { cloneDeep } from 'lodash-es'

// 引用声明
const props = defineProps({
  row: {
    type: Object,
    default: () => {
    }
  }
})

// 引用事件
const emits = defineEmits(['callback'])

// 响应式数据
const state = reactive({
  open: false,
  form: {
    speechToText: '',
    topicContent: '',
    publishCopy: '',
    postTopic: '',
    keyWordList: [],
    videoId: ''
  },
  loading: false,
  sendLoading: false
})

// 响应式数据解析
const { open, form, loading, sendLoading } = toRefs(state)

// 添加文案
const handleAddCopy = async () => {
  loading.value = true
  const [error, data] = await to(Api.video.videoEchoInfo(props.row.videoId))
  if (!error) {
    form.value = Object.assign({}, data, props.row, {
      keyWordList: data.keywordNames,
      postTopic: getTopicFiltering(data.postTopic)
    })

    if (!data.keywordNames) {
      if (props.row.topicContent || data.speechToText) {
        const params = { test: props.row.topicContent || data.speechToText }
        const [error, response] = await to(Api.video.videoEsIK(params))
        if (!error) {
          form.value.keyWordList = getTopicArrayToString(response)
        }
      }
    }

    await nextTick(() => {
      loading.value = false // 加载
      open.value = true // 开关
    })

  }
}

// 确定
const handleAddCopySubmit = async () => {
  sendLoading.value = true
  const dataForm = cloneDeep(form.value)
  dataForm.postTopic = getArrayToString(dataForm.postTopic)
  const [error, data] = await to(Api.video.videoAddCopy(dataForm))
  sendLoading.value = false
  if (!error && data === 1) {
    open.value = false
    message.success(`运营添加发布文案成功`)
    emits('callback')
  }
}

//关闭毁掉
const handleClose = (item: string) => {
  form.value.keyWordList = form.value.keyWordList.filter((record) => record !== item)
}

//转文字回调
const handleCallback = (reocrd: string) => {
  form.value.speechToText = reocrd
}

// 回调
const handleAddKeyCallback = (text: string, callback: () => void) => {
  if (form.value.keyWordList.indexOf(text) < 0) {
    form.value.keyWordList.push(text)
    callback()
  } else {
    message.warning('关键词重复了')
  }
}


//字符串变成是数组
const getTopicFiltering = (content: string[]) => {
  if (!content) return []
  return content
    .replace(/[\r\n\s]+/g, '')
    .split('#')
    .filter((item: string) => item)
}


//数组变成字符串
const getTopicArrayToString = (list: string[]) => {
  if (!list.length) return []
  let t = []
  for (const iterator of list) {
    let afile = iterator.replace(/\r\n/g, '')
    t.push(afile)
  }
  return t
}


// 数组变成字符串
const getArrayToString = (list: string | string[]) => {
  let str = ''
  if (!list && !list.length) return str
  for (const iterator of list) {
    str += '#' + iterator
  }
  return str
}


</script>

<template>
  <div>
    <a-button :icon="h(CopyOutlined)" :disabled="loading" type="primary" @click="handleAddCopy">添加文案</a-button>

    <a-modal
      v-model:open="open"
      :cancel-button-props="{ ghost: true }"
      :maskClosable="true"
      :okButtonProps="{loading:sendLoading}"
      title="视频发布信息"
      width="100%"
      @ok="handleAddCopySubmit"
    >
      <a-form ref="formRef" :model="form" layout="vertical" name="basic">
        <a-space class="pb-5">
          <PlayAudio :row="form" />
          <TurnText :row="form" @callback="handleCallback" />
        </a-space>

        <a-form-item v-if="form.speechToText" label="转换结果" name="username">
          <a-typography-paragraph :copyable="{ text: form.speechToText }">
            {{ form.speechToText }}
          </a-typography-paragraph>
        </a-form-item>

        <a-form-item label="话题内容" name="username">
          <a-typography-paragraph :copyable="{ text: form.topicContent }">
            {{ form.topicContent }}
          </a-typography-paragraph>
        </a-form-item>


        <a-form-item label="发布文案" name="publishCopy">
          <a-typography-paragraph v-model:content="form.publishCopy" editable />
        </a-form-item>

        <a-form-item extra="输入话题按回车健，自动生成一个话题，如果结束按Tab" label="发布话题" name="password">
          <a-select v-model:value="form.postTopic" mode="tags" placeholder="请输入话题"></a-select>
        </a-form-item>

        <a-form-item label="关键词" name="password">
          <a-space size="small" wrap>
            <a-tag
              v-for="(item, index) in form.keyWordList"
              :key="index"
              :bordered="false"
              closable
              color="pink"
              @close="handleClose(item)"
            >
              {{ item }}
            </a-tag>
            <AddKeys @callback="handleAddKeyCallback" />
          </a-space>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<style lang="less" scoped>

</style>
